import xbmcplugin, xbmcaddon
import hockeystreams, utils
import os
import datetime

# xbmc-hockey-streams
# author: craig mcnicholas
# contact: craig@designdotworks.co.uk

# deals with a bug where errors are thrown 
# if data directory does not exist.
addonId = 'plugin.video.xbmc-hockey-streams'
dataPath = 'special://profile/addon_data/' + addonId
if not os.path.exists: os.makedirs(dataPath)
addon = xbmcaddon.Addon(id = addonId)

# Method to draw the home screen
def HOME():
    print 'HOME()'
    utils.addDir(addon.getLocalizedString(100005), utils.Mode.ARCHIVES, '', None)
    utils.addDir(addon.getLocalizedString(100006), utils.Mode.LIVE, '', None)

# Method to draw the archives screen
def ARCHIVES():
    print 'ARCHIVES()'
    utils.addDir(addon.getLocalizedString(100007), utils.Mode.ARCHIVES_BY_DATE, '', None)
    utils.addDir(addon.getLocalizedString(100008), utils.Mode.ARCHIVES_BY_TEAM, '', None)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of years for archives
def ARCHIVES_BY_DATE():
    print 'ARCHIVES_BY_DATE()'

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the available dates
    dates = hockeystreams.availableDates(username, token)

    # Find unique years
    years = []
    for date in dates:
        if years.count(date.year) < 1:
            years.append(date.year)

    # Count total number of items for ui
    totalItems = len(years)
    
    # Add directories for years
    for year in years:
        params = {
            'year': str(year)
        }
        utils.addDir(str(year), utils.Mode.ARCHIVES_BY_DATE_YEAR, '', params, totalItems)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of months for a given year of archives
# @param year the year to obtain valid months for
def ARCHIVES_BY_DATE_YEAR(year):
    print 'ARCHIVES_BY_DATE_YEAR(year)'
    print 'Year: ' + str(year)

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the available dates
    dates = hockeystreams.availableDates(username, token)

    # Find unique months
    months = []
    for date in dates:
        if year == date.year and months.count(date.month) < 1:
            months.append(date.month)

    # Count total number of items for ui
    totalItems = len(months)

    # Add directories for months
    for month in months:
        # Create datetime for string formatting
        date = datetime.date(year, month, 1)
        params = {
            'year': str(year),
            'month': str(month)
        }
        utils.addDir(date.strftime('%B %Y'), utils.Mode.ARCHIVES_BY_DATE_MONTH, '', params, totalItems)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of days for a given year and month of archives
# @param year the year to obtain valid months for
# @param month the month to obtain valid days for
def ARCHIVES_BY_DATE_MONTH(year, month):
    print 'ARCHIVES_BY_DATE_MONTH(year, month)'
    print 'Year: ' + str(year)
    print 'Month: ' + str(month)

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the available dates
    dates = hockeystreams.availableDates(username, token)

    # Find unique days
    days = []
    for date in dates:
        if year == date.year and month == date.month and days.count(date.day) < 1:
            days.append(date.day)

    # Count total number of items for ui
    totalItems = len(days)

    # Add directories for days
    for day in days:
        # Create datetime for string formatting
        date = datetime.date(year, month, day)
        params = {
            'year': str(year),
            'month': str(month),
            'day': str(day)
        }
        utils.addDir(date.strftime('%A %d %B %Y'), utils.Mode.ARCHIVES_BY_DATE_DAY, '', params, totalItems)

# Method to draw the archives by date screen
# which scrapes the external source and presents
# a list of archived games for a given day
# @param username the username to login with
# @param password the password to login with
# @param year the year to obtain valid months for
# @param month the month to obtain valid days for
# @param day the day to obtain valid games for
def ARCHIVES_BY_DATE_DAY(username, password, year, month, day):
    print 'ARCHIVES_BY_DATE_DAY(username, password, year, month, day)'
    print 'Username: ' + username
    print 'Password: ' + password
    print 'Year: ' + str(year)
    print 'Month: ' + str(month)
    print 'Day: ' + str(day)

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the events
    date = datetime.date(year, month, day)
    events = hockeystreams.eventsForDate(username, token, date)

    params = {
        'year': str(year),
        'month': str(month),
        'day': str(day)
    }
    __listEvents(username, token, events, utils.Mode.ARCHIVES_BY_DATE_DAY, params)

# Method to draw the archives by team screen
# which scrapes the external source and presents
# a list of team names (or potentially events)
# @param username the username to login with
# @param password the password to login with
def ARCHIVES_BY_TEAM(username, password):
    print 'ARCHIVES_BY_TEAM(username, password)'
    print 'Username: ' + username
    print 'Password: ' + password

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the teams
    teams = hockeystreams.teams(username, token)

    # Count total number of items for ui
    totalItems = len(teams)

    # Add directories for teams
    for team in teams:
        params = {
            'team': team.url
        }
        utils.addDir(team.name, utils.Mode.ARCHIVES_BY_TEAM_EVENTS, '', params, totalItems)

# Method to draw the archives by team screen
# which scrapes the external source and presents
# a list of events for a given team
# @param username the username to login with
# @param password the password to login with
# @param team the team to find the events for
def ARCHIVES_BY_TEAM_EVENTS(username, password, team):
    print 'ARCHIVES_BY_TEAM_EVENTS(username, password, team)'
    print 'Username: ' + username
    print 'Password: ' + password
    print 'Team: ' + team

    # Perform login
    token = hockeystreams.login(username, password)

    # Retrieve the team events
    events = hockeystreams.eventsForTeam(username, token, team)

    params = {
        'team': team
    }
    __listEvents(username, token, events, utils.Mode.ARCHIVES_BY_TEAM_EVENTS, params)

# Method to list a series of event streams
# @param username the username to login with
# @param token the token to login with
# @param events the list of events to display
# @param mode the mode to return to if stream is invalid
# @param params the params to pass if stream is invalid
def __listEvents(username, token, events, mode, params):
    # Count total number of items for ui, this could potentially be
    # less if the url is invalid
    totalItems = len(events)

    # Add invalid flag to params
    params['invalid'] = 'True'

    # Add directories for events
    for event in events:
        streamUrl = hockeystreams.eventStream(username, token, event)        
        title = (event.time if event.time != None else '') + ' ' + event.league + ': '+ event.awayTeam + ' @ ' + event.homeTeam
        if streamUrl != None:
            utils.addLink(('[LIVE] ' if event.onDemand != True else '[On Demand] ') + title, streamUrl, '', totalItems)
        else:
            utils.addDir('[' + addon.getLocalizedString(100009) + '] ' + title, mode, '', params, totalItems)

# Method to draw the live screen
# which scrapes the external source and presents
# a list of live or future events
# @param username the username to login with
# @param password the password to login with
def LIVE(username, password):
    print 'LIVE(username, password)'
    print 'Username: ' + username
    print 'Password: ' + password

    # Perform login
    token = hockeystreams.login(username, password)

    # Find live events
    events = hockeystreams.liveEvents(username, token)

    params = {}
    __listEvents(username, token, events, utils.Mode.LIVE, params)
	
# Load settings
username = addon.getSetting('username')
password = addon.getSetting('password')

# Load the parameters
params = utils.getParams()

# Print params for debugging
for k, v in params.iteritems():
    print k + ': ' + v

# Attempt to parse mode
mode = utils.parseParamInt(params, 'mode')

# Attempt to parse other variables
year = utils.parseParamInt(params, 'year')
month = utils.parseParamInt(params, 'month')
day = utils.parseParamInt(params, 'day')
team = utils.parseParamString(params, 'team')
invalid = utils.parseParamString(params, 'invalid')

# First check invalid stream else find mode and execute
invalid = invalid != None and invalid.lower() == 'true'
if invalid:
    print 'Stream unavailable, please check hockeystreams.com for wmv stream availability.'
    utils.showMessage(addon.getLocalizedString(100003), addon.getLocalizedString(100004))

# Check if username/password has been provided
if username == None or len(username) < 1 or password == None or len(password) < 1:
    addon.openSettings()

# Set flags for end of directory
updateListing = invalid
cacheToDisc = True

if mode == None or mode == utils.Mode.HOME:
    HOME()
elif mode == utils.Mode.ARCHIVES:
    ARCHIVES()
elif mode == utils.Mode.ARCHIVES_BY_DATE:
    ARCHIVES_BY_DATE()
elif mode == utils.Mode.ARCHIVES_BY_DATE_YEAR:
    ARCHIVES_BY_DATE_YEAR(year)
elif mode == utils.Mode.ARCHIVES_BY_DATE_MONTH:
    ARCHIVES_BY_DATE_MONTH(year, month)
elif mode == utils.Mode.ARCHIVES_BY_DATE_DAY:
    ARCHIVES_BY_DATE_DAY(username, password, year, month, day)
elif mode == utils.Mode.ARCHIVES_BY_TEAM:
    ARCHIVES_BY_TEAM(username, password)
elif mode == utils.Mode.ARCHIVES_BY_TEAM_EVENTS:
    ARCHIVES_BY_TEAM_EVENTS(username, password, team)
elif mode == utils.Mode.LIVE:
    LIVE(username, password)
    cacheToDisc = False # Never cache this view

# Signal end of directory
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc = cacheToDisc, updateListing = updateListing)
